﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Threading;

namespace 子域名扫描
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
            this.dataGridView1.RowPostPaint += new System.Windows.Forms.DataGridViewRowPostPaintEventHandler(this.dataGridView1_RowPostPaint);
        }

        private Thread th;

        private void button1_Click(object sender, EventArgs e)
        {
            DispatcherTimer timer = new DispatcherTimer();
            timer.Tick += new EventHandler(timer1_Tick);
            timer.Interval = TimeSpan.FromSeconds(0.1);   //设置刷新的间隔时间
            timer.Start();

            Process myProcess = Process.GetCurrentProcess();//获取该进程
            ProcessThreadCollection PTC = myProcess.Threads;//获取其关联的线程，包括主线程
            int num = PTC.Count;//获取线程数量
            //button1.Text = "结束扫描";
            button1.Enabled = false;
            if (comboBox1.Text == "自定义")
            {
                MessageBox.Show("请输入线程数，该方法是调用线程池的方式，你电脑能带的走 输入的值就大！");
                return;
            }

            if (textBox2.Text == string.Empty)
            {
                MessageBox.Show("扫描地址不能为空！");
                return;
            }
            if(comboBox1.Text == "多线程")
            {
                //执行多线程的方式
                th = new Thread(GetDxc);
                th.IsBackground = false;
                th.Start();

                //if (button1.Text == "结束扫描")
                //{
                //    thread.Abort();
                //}
            }
            else
            {
                //执行自定义线程的方式
                th = new Thread(GetZxc);
                th.IsBackground = false;
                th.Start();
            }
            
        }
        ///LoadPage方法
        /// <summary>
        /// loaddpage方法
        /// </summary>
        //多线程的方式
        public int secrv = 0;
        public void GetDxc()
        {
            label5.Text = "正在扫描中";
            //执行子域名扫描 https的方式
            string path = "yuming.txt";
            StreamReader sr = new StreamReader(path, Encoding.Default);
            String line;
            while ((line = sr.ReadLine()) != null)
            {
                string s1 = line;
                string url = textBox2.Text;//先去除获取到 只保留baidu.com
                var temp = url.Split('.');//拆分字符串
                                          //获取最后 . 两位的字符
                string str = temp.Length > 2 ? temp[temp.Length - 2] + "." + temp[temp.Length - 1] : "";
                try
                {
                    Thread.Sleep(200);//避免线程卡死
                    Ping p1 = new Ping();
                    PingReply reply = p1.Send(s1 + str); //发送主机名或Ip地址

                    StringBuilder sbuilder;
                    if (reply.Status == IPStatus.Success)
                    {
                        sbuilder = new StringBuilder();
                        sbuilder.AppendLine(string.Format("Address: {0} ", reply.Address.ToString()));
                        sbuilder.AppendLine(string.Format("RoundTrip time: {0} ", reply.RoundtripTime));
                        sbuilder.AppendLine(string.Format("Time to live: {0} ", reply.Options.Ttl));
                        sbuilder.AppendLine(string.Format("Don't fragment: {0} ", reply.Options.DontFragment));
                        sbuilder.AppendLine(string.Format("Buffer size: {0} ", reply.Buffer.Length));
                        string s11 = reply.Address.ToString();//IP地址
                        string s2 = reply.RoundtripTime.ToString();
                        string s3 = reply.Options.Ttl.ToString();
                        string s4 = reply.Options.DontFragment.ToString();
                        string s5 = reply.Buffer.Length.ToString();
                        string s0 = url + str;
                        Console.WriteLine("扫描时间：" + DateTime.Now + "   ------   " + s0 + "   ---   " + "IP地址：" + s11 + "往返时间：" + s2 + "存活时间：" + s3 + "\r\n");
                        dataGridView1.Rows.Add(s0, s11, s2, s3, s4, s5);
                        Console.WriteLine(sbuilder.ToString());
                    }
                    else if (reply.Status == IPStatus.TimedOut)
                    {
                        Console.WriteLine("超时");
                    }
                    else
                    {
                        Console.WriteLine("失败");
                    }
                    //Console.WriteLine(s1 + str);
                    //HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://" + s1 + str);//从新构建请求
                    //Console.WriteLine(req);
                    //req.Method = "HEAD";
                    //int swgf = Convert.ToInt32(textBox1.Text);//获取int类型格式
                    //secrv = swgf * 1000;
                    //req.Timeout = Convert.ToInt32(secrv.ToString());
                    //req.AllowAutoRedirect = false;
                    ////将INT 转换为 String
                    //int amount;
                    //if (int.TryParse(textBox1.Text, out amount))
                    //{
                    //    req.Timeout = amount;
                    //}
                    ////req.Timeout = 100;//设置超时
                    //HttpWebResponse reponse = (HttpWebResponse)req.GetResponse();
                    //var res = reponse;
                    ////获取IP地址
                    //UriBuilder ub = new UriBuilder(s1 + str);
                    //string host = (ub.Host.Replace("https://", "http://"));
                    //IPAddress[] addresslist = Dns.GetHostAddresses(host);
                    //foreach (IPAddress theaddress in addresslist)
                    //{
                    //    if (res.StatusCode == HttpStatusCode.OK)
                    //    {
                    //        Console.WriteLine("二级域名：" + host + "\r\n" + "IP地址：" + theaddress.ToString() + "\r\n");
                    //        //将成功地址 记录到datagridview1中
                    //        dataGridView1.Rows.Add(host, theaddress.ToString(), HttpStatusCode.OK);
                    //    }
                    //    else
                    //    {
                    //        Console.WriteLine("二级域名：" + host + "\r\n" + "IP地址：" + theaddress.ToString() + "\r\n");
                    //    }
                    //}
                }
                catch (Exception ex)
                {
                    //Console.WriteLine(ex);
                    //MessageBox.Show("错误提示：" + ex);
                }
            }
            Console.WriteLine("线程结束");
            label5.Text = "执行完毕";
            if(label5.Text == "执行完毕")
            {
                button1.Text = "开始扫描";
                button1.Enabled = true;
            }
        }
        public void GetZxc()
        {
            label5.Text = "正在扫描中";
            int amount;
            if (int.TryParse(comboBox1.Text, out amount))
            {
                int numxc = amount;
            }
            ThreadPool.SetMinThreads(20, 100);
            ThreadPool.SetMaxThreads(5, 5);
            for (int i = 0; i <= 0; i++)
            {
                //方式一
                ThreadPool.QueueUserWorkItem(new WaitCallback(CtuIko), i.ToString());//创建线程去执行CtuIko的公共方法
                //方式二
                //Thread thread = new Thread(CtuIko);
                //thread.Start();
            }
        }
        public void CtuIko(object obj)
        {
            
            label5.Text = "正在扫描中";
            //执行子域名扫描 https的方式
            string path = "yuming.txt";
            StreamReader sr = new StreamReader(path, Encoding.Default);
            String line;
            while ((line = sr.ReadLine()) != null)
            {
                string s1 = line;
                string url = textBox2.Text;//先去除获取到 只保留baidu.com
                var temp = url.Split('.');//拆分字符串
                                          //获取最后 . 两位的字符
                string str = temp.Length > 2 ? temp[temp.Length - 2] + "." + temp[temp.Length - 1] : "";
                try
                {
                    Thread.Sleep(50);
                    Console.WriteLine(s1 + str);
                    HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://" + s1 + str);//从新构建请求
                    Console.WriteLine(req);
                    req.Method = "HEAD";
                    req.AllowAutoRedirect = false;
                    //将INT 转换为 String
                    int amount;
                    if (int.TryParse(textBox1.Text, out amount))
                    {
                        req.Timeout = amount;
                    }
                    //req.Timeout = 100;//设置超时
                    HttpWebResponse reponse = (HttpWebResponse)req.GetResponse();
                    var res = reponse;
                    //获取IP地址
                    UriBuilder ub = new UriBuilder(s1 + str);
                    string host = (ub.Host.Replace("https://", "http://"));
                    IPAddress[] addresslist = Dns.GetHostAddresses(host);
                    foreach (IPAddress theaddress in addresslist)
                    {
                        if (res.StatusCode == HttpStatusCode.OK)
                        {
                            Console.WriteLine("二级域名：" + host + "\r\n" + "IP地址：" + theaddress.ToString() + "\r\n");
                            //将成功地址 记录到datagridview1中
                            dataGridView1.Rows.Add(host, theaddress.ToString(), HttpStatusCode.OK);
                        }
                        else
                        {
                            Console.WriteLine("二级域名：" + host + "\r\n" + "IP地址：" + theaddress.ToString() + "\r\n");
                        }
                    }
                }
                catch (Exception ex)
                {
                    //Console.WriteLine(ex);
                    //MessageBox.Show("错误提示：" + ex);
                }
            }
            Console.WriteLine("线程结束");
            label5.Text = "执行完毕";
            if (label5.Text == "执行完毕")
            {
                button1.Text = "开始扫描";
                button1.Enabled = true;
            }
        }
        private void button2_Click(object sender, EventArgs e)
        {
            //结束线程

        }

        private void button2_Click_1(object sender, EventArgs e)
        {
            if(th.ThreadState != System.Threading.ThreadState.Suspended)
            {
                th.Abort();//终止线程
                label5.Text = "线程已终止";
                button1.Enabled = true;
            }
        }

        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            //增加序列号的方法  在 RowPostPaint 中
            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,
            e.RowBounds.Location.Y,
            dataGridView1.RowHeadersWidth - 4,
            e.RowBounds.Height);

            TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(),
            dataGridView1.RowHeadersDefaultCellStyle.Font,
            rectangle,
            dataGridView1.RowHeadersDefaultCellStyle.ForeColor,
            TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            //去除空白行
            dataGridView1.AllowUserToAddRows = false;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            Process myProcess = Process.GetCurrentProcess();//获取该进程
            ProcessThreadCollection PTC = myProcess.Threads;//获取其关联的线程，包括主线程
            //int num = 0;
            //foreach (ProcessThread item in PTC)
            //{
            //    if (item.ThreadState == System.Diagnostics.ThreadState.Wait)
            //        if (item.WaitReason == ThreadWaitReason.UserRequest)
            //            continue;
            //    num++;
            //}
            int num = PTC.Count;//获取线程数量
            toolStripStatusLabel2.Text = num.ToString();
            toolStripStatusLabel4.Text = num.ToString();
            if(th.ThreadState == System.Threading.ThreadState.Aborted)
            {
                toolStripStatusLabel2.Text = "0";
                toolStripStatusLabel4.Text = "0";
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            
        }

        private void button4_Click(object sender, EventArgs e)
        {
           
        }

        private void button5_Click(object sender, EventArgs e)
        {
            
        }

        private void button6_Click(object sender, EventArgs e)
        {
            
        }
        /// <summary>
        /// 增加数据库方法
        /// </summary>
        //public void ZwebRootScam()
        //{
        //    //执行子域名扫描 https的方式
        //    LogMessage("创建时间：" + DateTime.Now + "   -------   " + "正在创建子域名扫描线程" + "\r\n");
        //    string url = linkLabel1.Text;//获取域名
        //    var temp = url.Split('.');//拆分字符串
        //                              //获取最后 . 两位的字符
        //    string str = temp.Length > 2 ? temp[temp.Length - 2] + "." + temp[temp.Length - 1] : "";
        //    string loop = Sec_SqlClientHelp.Sqlclient(Sec_SqlClientApi.H1);
        //    SQLiteConnection dataConn1 = new SQLiteConnection(loop);
        //    dataConn1.Open();
        //    try
        //    {
        //        if (dataConn1.State == ConnectionState.Open)
        //        {
        //            //string sql = "SELECT * FROM Sec_loophole 'Stack-Payload'";//查询漏洞有效载荷数据
        //            string sql = Sec_SqlClientHelp.ZdomainInfo(Sec_SqlClientApi.H8);//查询漏洞有效载荷数据
        //            SQLiteCommand command1 = new SQLiteCommand(sql, dataConn1);
        //            using (SQLiteDataReader dr = command1.ExecuteReader(CommandBehavior.CloseConnection))
        //            {
        //                while (dr.Read())
        //                {
        //                    string dics = dr["domain"].ToString();//循环读取的子域名数据
        //                    try
        //                    {
        //                        Ping p1 = new Ping();
        //                        PingReply reply = p1.Send(dics + str); //发送主机名或Ip地址

        //                        StringBuilder sbuilder;
        //                        if (reply.Status == IPStatus.Success)
        //                        {
        //                            sbuilder = new StringBuilder();
        //                            sbuilder.AppendLine(string.Format("Address: {0} ", reply.Address.ToString()));
        //                            sbuilder.AppendLine(string.Format("RoundTrip time: {0} ", reply.RoundtripTime));
        //                            sbuilder.AppendLine(string.Format("Time to live: {0} ", reply.Options.Ttl));
        //                            sbuilder.AppendLine(string.Format("Don't fragment: {0} ", reply.Options.DontFragment));
        //                            sbuilder.AppendLine(string.Format("Buffer size: {0} ", reply.Buffer.Length));
        //                            string s1 = reply.Address.ToString();//IP地址
        //                            string s2 = reply.RoundtripTime.ToString();
        //                            string s3 = reply.Options.Ttl.ToString();
        //                            string s4 = reply.Options.DontFragment.ToString();
        //                            string s5 = reply.Buffer.Length.ToString();
        //                            string s0 = dics + str;
        //                            LogError("扫描时间：" + DateTime.Now + "   ------   " + s0 + "   ---   " + "IP地址：" + s1 + "往返时间：" + s2 + "存活时间：" + s3 + "\r\n");
        //                            dataGridView1.Rows.Add(s0, s1, s2, s3, s4, s5);
        //                            Console.WriteLine(sbuilder.ToString());
        //                        }
        //                        else if (reply.Status == IPStatus.TimedOut)
        //                        {
        //                            Console.WriteLine("超时");
        //                        }
        //                        else
        //                        {
        //                            Console.WriteLine("失败");
        //                        }
        //                        //for(int i =0;i <= dics.Length; i++)
        //                        //{

        //                        //}
        //                        //这里采用爬虫的方式去进行请求
        //                        //HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create("http://" + dics + str);
        //                        //httpReq.Method = "GET";//获取请求方式
        //                        //httpReq.Accept = "*/*";
        //                        //httpReq.ServicePoint.Expect100Continue = false;//加快载入速度
        //                        //httpReq.ServicePoint.UseNagleAlgorithm = false;//禁止nagle算法加快载入速度
        //                        //httpReq.AllowWriteStreamBuffering = false;//禁止缓冲加快载入速度
        //                        //httpReq.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");//定义gzip压缩页面支持
        //                        //httpReq.ContentType = "application/x-www-form-urlencoded";//定义文档类型及编码
        //                        //httpReq.AllowAutoRedirect = false;//禁止自动跳转
        //                        //httpReq.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36";
        //                        //httpReq.Timeout = 2000;//请求超时
        //                        //httpReq.KeepAlive = true;//启用长连接
        //                        //httpReq.ServicePoint.ConnectionLimit = int.MaxValue;//定义最大连接数
        //                        //HttpWebResponse response = (HttpWebResponse)httpReq.GetResponse();
        //                        //var v = response.StatusCode;//初始化状态
        //                        ////获取IP地址
        //                        //UriBuilder ub = new UriBuilder(str);
        //                        //string host = (ub.Host.Replace("https://", "http://"));
        //                        //IPAddress[] addresslist = Dns.GetHostAddresses(host);
        //                        //for (int i = 0; i < dics.Length; i++)
        //                        //{
        //                        //    if (v == HttpStatusCode.OK)
        //                        //    {
        //                        //        AppLog.WriteInfo("子域名扫描：" + "扫描时间：" + DateTime.Now + "   ------   " + dics[i] + str[i] + "   ---   " + "状态：" + HttpStatusCode.OK, true);
        //                        //        Console.WriteLine("扫描时间：" + DateTime.Now + "   ------   " + dics[i] + str + "   ---   " + "状态：" + HttpStatusCode.OK);
        //                        //        LogMessage("扫描时间：" + DateTime.Now + "   ------   " + dics[i] + str + "   ---   " + "状态：" + HttpStatusCode.OK + "\r\n");
        //                        //        foreach (IPAddress theaddress in addresslist)
        //                        //        {
        //                        //            dataGridView1.Rows.Add(dics[i] + str, theaddress.ToString(), HttpStatusCode.OK);
        //                        //        }
        //                        //        //dataGridView1.Rows.Add(dics[i] + str, s1, HttpStatusCode.OK);
        //                        //        RquestCount++;
        //                        //        toolStripStatusLabel8.Text = RquestCount.ToString();
        //                        //    }
        //                        //}

        //                    }
        //                    catch (Exception ex)
        //                    {
        //                        AppLog.WriteError("后台扫描：" + ex.ToString(), true);//记录后台扫描错误日志
        //                        LogWarning("扫描时间：" + DateTime.Now + "   ------   " + dics + str + "   ---   " + "状态：" + "域名无法访问" + "\r\n");
        //                        Console.WriteLine(ex.ToString());
        //                        Console.WriteLine("超时");
        //                        RquestCount++;
        //                        toolStripStatusLabel8.Text = RquestCount.ToString();
        //                    }
        //                }
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        AppLog.WriteError("后台扫描：" + ex.ToString(), true);//记录后台扫描错误日志
        //        Console.WriteLine(ex.ToString());
        //        RquestCount++;
        //        toolStripStatusLabel8.Text = RquestCount.ToString();
        //    }
        //    //return;
        //    //string path = "yuming.txt";
        //    //StreamReader sr = new StreamReader(path, Encoding.Default);
        //    //String line;
        //    //LogMessage("创建时间：" + DateTime.Now + "   -------   " + "正在读取子域名" + "\r\n");
        //    //LogMessage("创建时间：" + DateTime.Now + "   -------   " + "正在扫描子域名" + "\r\n");
        //    //while ((line = sr.ReadLine()) != null)
        //    //{
        //    //    string s1 = line;
        //    //    string url = linkLabel1.Text;//先去除获取到 只保留baidu.com
        //    //    var temp = url.Split('.');//拆分字符串
        //    //                              //获取最后 . 两位的字符
        //    //    string str = temp.Length > 2 ? temp[temp.Length - 2] + "." + temp[temp.Length - 1] : "";
        //    //    try
        //    //    {
        //    //        Thread.Sleep(500);//不设置的情况下 会卡死
        //    //        Console.WriteLine(s1 + str);
        //    //        HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://" + s1 + str);//从新构建请求
        //    //        Console.WriteLine(req);
        //    //        req.Method = "HEAD";
        //    //        req.AllowAutoRedirect = false;
        //    //        //req.Timeout = 200;//设置超时
        //    //        HttpWebResponse reponse = (HttpWebResponse)req.GetResponse();
        //    //        var res = reponse;
        //    //        //获取IP地址
        //    //        UriBuilder ub = new UriBuilder(s1 + str);
        //    //        string host = (ub.Host.Replace("https://", "http://"));
        //    //        IPAddress[] addresslist = Dns.GetHostAddresses(host);
        //    //        foreach (IPAddress theaddress in addresslist)
        //    //        {
        //    //            if (res.StatusCode == HttpStatusCode.OK)
        //    //            {
        //    //                AppLog.WriteInfo("二级域名：" + host + "\r\n" + "IP地址：" + theaddress.ToString() + "\r\n", true);
        //    //                Console.WriteLine("二级域名：" + host + "\r\n" + "IP地址：" + theaddress.ToString() + "\r\n");
        //    //                LogMessage("创建时间：" + DateTime.Now + "   -------   " + "二级域名：" + host + "\r\n");
        //    //                //将成功地址 记录到datagridview1中
        //    //                dataGridView1.Rows.Add(host, theaddress.ToString(), HttpStatusCode.OK);
        //    //            }
        //    //            else
        //    //            {
        //    //                AppLog.WriteError("二级域名：" + host + "\r\n" + "IP地址：" + theaddress.ToString() + "\r\n", true);
        //    //                Console.WriteLine("二级域名：" + host + "\r\n" + "IP地址：" + theaddress.ToString() + "\r\n");
        //    //            }
        //    //        }
        //    //        label6.Text = "%40";

        //    //        //progressBar1.Minimum = 40;
        //    //        progressBar1.Value = 40;
        //    //        //progressBar1.Maximum = 40;
        //    //    }
        //    //    catch (Exception ex)
        //    //    {
        //    //        AppLog.WriteError("错误提示：" + "\r\n" + "时间：" + DateTime.Now + "\r\n" + ex, true);
        //    //    }
        //    //}
        //    //if (this.InvokeRequired)
        //    //{
        //    //    //创建一个线程去添加节点
        //    //    CreateNodeDelegate1 createNodeDelegate1 = new CreateNodeDelegate1(Views);
        //    //    this.Invoke(createNodeDelegate1);
        //    //}
        //    label6.Text = "40%";
        //    progressBar1.Value = 40;
        //    LogMessage("创建时间：" + DateTime.Now + "   -------   " + "子域名扫描结束" + "\r\n");
        //    LogMessage("创建时间：" + DateTime.Now + "   -------   " + "任务线程自动结束" + "\r\n");
        //    System.Threading.Thread.Sleep(3000);
        //    //创建后台扫描线程
        //    WebPathscan = new Thread(FscanWeb);
        //    //PortScan.IsBackground = false;
        //    WebPathscan.Start();
        //}
    }
}
